<script setup lang="ts">
import { ref ,Ref} from 'vue'
import type { UploadProps, UploadUserFile, ElUpload, UploadRequestOptions } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus';
import { uploadPicture } from '../api/uploadApi'

const fileList = ref<UploadUserFile[]>([])
//图片预览
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
//自定义上传方法
const customUpload = async (options: UploadRequestOptions) => {
  const formData = new FormData()
  formData.append('file', options.file as File)
  try {
    const url = await uploadPicture(formData)
    ElMessage.success('上传成功')
    // 调用 onSuccess 回调，传递 URL
    options.onSuccess(url)
    dialogImageUrl.value = url

  } catch (error: any) {
    // 显示上传失败的消息
    ElMessage.error(error.message || '上传失败!');
    // 调用 onError 回调，传递错误对象
    options. onError(error);
  }
}
//处理文件移除
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log('移除的文件:', file);
  console.log('当前文件列表:', uploadFiles);
}
//处理文件预览

const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log('预览的文件:', uploadFile);
  dialogVisible.value = true;
}
//处理超出限制的文件
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(
    `最多只能上传 1 个文件，你这次选择了 ${files.length} 个文件，总共已选择 ${files.length + uploadFiles.length} 个文件`
  );
}
//移除前的确认
const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `确定移除 ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  )
}
/**
 * 上传前的文件大小验证
 */
 const beforeUpload = (file: File) => {
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    ElMessage.error('上传文件大小不能超过 10MB!');
  }
  return isLt10M;
};
</script>

<template>
  <el-button>获取项目列表</el-button>
  <el-upload 
    v-model:file-list="fileList" 
    class="upload-demo" 
    :http-request="customUpload" 
    multiple
    :on-preview="handlePreview" 
    :on-remove="handleRemove" 
    :before-remove="beforeRemove" 
    :limit="1"
    :on-exceed="handleExceed"
    :before-upload="beforeUpload">

    <!-- <img v-if="dialogImageUrl" :src="dialogImageUrl" class="avatar" /> -->
    <el-button type="primary">上传</el-button>

  </el-upload>
  <el-dialog v-model="dialogVisible" style="width: 480px; height: auto;">
     <img :src="dialogImageUrl" style="width: 400px; height: auto;" />
  </el-dialog>

</template>


<style scoped>
  
</style>
